package com.plian.system.service.pf.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.entity.pf.BasePerformanceEffect;
import com.plian.system.entity.pf.PerformanceEffectDetail;
import com.plian.system.enumeratea.BusinessIndicatorsStatus;
import com.plian.system.mapper.pf.BasePerformanceEffectMapper;
import com.plian.system.model.ObjResult;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.service.pf.IPerformanceEffectChangeService;
import com.plian.system.service.pf.IPerformanceEffectDetailService;
import com.plian.system.vo.pf.BasePerformanceEffectVO;
import com.plian.system.wrapper.pf.BasePerformanceEffectWrapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * @Author: Take-off
 * @Description: TODO
 * @Date: 2023/1/31 2:12 PM
 * @Version: 1.0
 **/
@Service
@AllArgsConstructor
public class PerformanceEffectChangeServiceImpl extends BaseServiceImpl<BasePerformanceEffectMapper, BasePerformanceEffect> implements IPerformanceEffectChangeService, BaseFlowService {


    private IPerformanceEffectDetailService effectDetailService;

    private BasePerformanceEffectWrapper basePerformanceEffectWrapper;

    @Override
    public boolean saveOrUpdate(BasePerformanceEffect basePerformanceEffect) {
        if (!Optional.ofNullable(basePerformanceEffect.getId()).isPresent()) {
            basePerformanceEffect.setFormType(String.valueOf(FormTypeConstant.PF_PERFORMANCE_EFFECT_CHANGE));
            basePerformanceEffect.setVersion(basePerformanceEffect.getVersion() + 1);
            basePerformanceEffect.setIsLatest(1);
            basePerformanceEffect.setIndicatorStatus(BusinessIndicatorsStatus.CHANGE_AUDIT.getStatus());
            updateLangStatus(basePerformanceEffect.getInitialId(), BusinessIndicatorsStatus.CHANGE_AUDIT.getStatus());

        }
        return super.saveOrUpdate(basePerformanceEffect);
    }

    @Override
    @Transactional(rollbackFor=RuntimeException.class)
    public boolean deleteLogic(List<Long> ids) {
        for (Long id : ids) {
            BasePerformanceEffect basePerformanceEffect = getById(id);
            if (basePerformanceEffect == null) {
                return false;
            }
            updateLangStatus(basePerformanceEffect.getInitialId(), BusinessIndicatorsStatus.ADJUSTABLE.getStatus());
            update(Wrappers.<BasePerformanceEffect>lambdaUpdate()
                    .eq(BasePerformanceEffect::getInitialId, basePerformanceEffect.getInitialId())
                    .eq(BasePerformanceEffect::getVersion, basePerformanceEffect.getVersion() - 1)
                    .set(BasePerformanceEffect::getIsLatest, 2));
        }
        boolean result = super.deleteLogic(ids);
        if (result){
            effectDetailService.deleteByParentId(ids);
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor=RuntimeException.class)
    public boolean submit(BasePerformanceEffect basePerformanceEffect) {
        boolean result = saveOrUpdate(basePerformanceEffect);
        if (result){
            List<PerformanceEffectDetail> performanceEffectDetails = basePerformanceEffect.getPerformanceEffectDetails();
            if (CollectionUtil.isNotEmpty(performanceEffectDetails)){
                for (PerformanceEffectDetail effectDetail : performanceEffectDetails){
                    if (effectDetail.getId() != null &&
                            Optional.ofNullable(effectDetail.getIsDeleted()).isPresent() && effectDetail.getIsDeleted().intValue() == 1) {
                        effectDetailService.removeById(effectDetail.getId());
                    }else {
                        effectDetail.setBasePerformanceId(basePerformanceEffect.getId());
                        effectDetailService.saveOrUpdate(effectDetail);
                    }
                }
            }
        }
        return result;
    }

    @Override
    public HashMap<String,Object> commit(String id) {
        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);

        //将需要提交的流程变量返回，用于工作流侧
        return new HashMap<String,Object>();
    }

    @Override
    public Boolean finish(String id) {
        BasePerformanceEffect performanceEffect = getById(id);
        updateLangStatus(performanceEffect.getInitialId(), BusinessIndicatorsStatus.ADJUSTABLE.getStatus());
        updateIsLatest(performanceEffect.getInitialId());
        performanceEffect.setApprovedUser(TokenUtil.getTokenUserId());
        Date now = DateUtil.now();
        performanceEffect.setApprovedTime(now);
        performanceEffect.setIsLatest(2);
        performanceEffect.setIndicatorStatus(BusinessIndicatorsStatus.ADJUSTABLE.getStatus());
        updateById(performanceEffect);
        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
    }

    @Override
    public Boolean reject(String id, int formState,String comment) {
        return handleStatus(Long.valueOf(id), formState);
    }

    @Override
    public List<PageData> findByIds(List<String> formIds) {
        LambdaQueryWrapper<BasePerformanceEffect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(BasePerformanceEffect::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
        List<BasePerformanceEffect> performanceEffects = list(queryWrapper);
        List<BasePerformanceEffectVO> performanceEffectVOS = basePerformanceEffectWrapper.entityToVO(performanceEffects);
        List<PageData> pageDataList = new ArrayList<>();
        try{
            if (CollectionUtil.isNotEmpty(performanceEffectVOS)){
                for (BasePerformanceEffectVO vo : performanceEffectVOS){
                    PageData pd = new PageData();
                    pd.put("id", vo.getId());
                    pd.put("UNITNAME", vo.getReportOfficeName());
                    pd.put("APPLICANTNAME", vo.getCreateUserName());
                    pd.put("applicantId", vo.getCreateUser());
                    pd.put("applyOrganizationId", vo.getReportOffice());
                    pd.put("formType", FormTypeConstant.PF_PERFORMANCE_EFFECT_CHANGE);
                    pd.put("orgName", vo.getReportOfficeName());
                    pageDataList.add(pd);
                }
            }

            return pageDataList;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return pageDataList;
    }

    @Override
    public List<Integer> getFormType() {
        return Arrays.asList(FormTypeConstant.PF_PERFORMANCE_EFFECT_CHANGE);
    }

    @Override
    public void goBackToStash(String formId) {
        Long id = Long.valueOf(formId);
        List<BasePerformanceEffect> performanceEffects = list(new LambdaQueryWrapper<BasePerformanceEffect>().eq(BasePerformanceEffect::getInitialId, id));
        if (CollectionUtil.isNotEmpty(performanceEffects) && performanceEffects.size() > 1){
            throw new MyRuntimeException(new ObjResult("该单据已进行其他操作，无法退回！"));
        }
        BasePerformanceEffect performanceEffect = getById(id);
        if (performanceEffect.getStatus() == FormStatusConstant.FINISH){
            LambdaUpdateWrapper<BasePerformanceEffect> updateWrapper = new LambdaUpdateWrapper<>();
            update(updateWrapper.eq(BasePerformanceEffect::getId, id)
                    .set(BasePerformanceEffect::getApprovedUser, null).set(BasePerformanceEffect::getApprovedTime, null)
                    .set(BasePerformanceEffect::getIndicatorStatus, null));
        }

        handleStatus(Long.valueOf(formId), UNREVIEWED);
    }

    /**
     * 统一处理状态机事件方法
     *
     * @param id          主键
     * @param updateStatus  更新状态
     * @return boolean
     */
    private Boolean handleStatus(Long id, int updateStatus) {
        try {
            BasePerformanceEffect tripleMeeting = getById(id);
            /**
             * 设置审批人和审批时间
             */
            if (updateStatus == FormStatusConstant.FINISH){
                tripleMeeting.setApprovedUser(TokenUtil.getTokenUserId());
                Date now = DateUtil.now();
                tripleMeeting.setApprovedTime(now);
            }
            tripleMeeting.setStatus(updateStatus);
            updateById(tripleMeeting);
            return true;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return false;
        }
    }

    private void updateLangStatus(Long initialId, int landStatus){
        update(new LambdaUpdateWrapper<BasePerformanceEffect>().eq(BasePerformanceEffect::getInitialId, initialId).set(BasePerformanceEffect::getIndicatorStatus, landStatus));
    }

    private void updateIsLatest(Long initialId){
        update(new LambdaUpdateWrapper<BasePerformanceEffect>().eq(BasePerformanceEffect::getInitialId, initialId)
                .eq(BasePerformanceEffect::getIsLatest, 2).set(BasePerformanceEffect::getIsLatest, 1));
    }

}
